package com.example.moban.utils.updata;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.example.moban.BuildConfig;

import java.io.File;

/**
 * @author Administrator
 */
public class VersionUpdateUtils {


    private Context context;
    private long mTaskId;
    private DownloadManager downloadManager;
    private String versionName;
    private DownloadFinishInterface downloadFinishInterface;

    public VersionUpdateUtils(Context context) {
        this.context = context;
    }

    public void setDownloadFinishInterface(DownloadFinishInterface downloadFinishInterface) {
        this.downloadFinishInterface = downloadFinishInterface;
    }

    /**
     * 使用系统下载器下载
     */
    public void downloadApk(String versionUrl) {
        this.versionName = System.currentTimeMillis() + "";
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionUrl));
        //漫游网络是否可以下载
        request.setAllowedOverRoaming(false);

        //设置文件类型，可以在下载结束后自动打开该文件
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(versionUrl));
        request.setMimeType(mimeString);

        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setVisibleInDownloadsUi(true);

        //sdcard的目录下的download文件夹，必须设置
        request.setDestinationInExternalPublicDir("/download/", versionName);
//        request.setDestinationInExternalPublicDir(getExternalCacheDir().getAbsolutePath(), "download"); 解析包错问题（未下载）
//        request.setDestinationInExternalFilesDir(),也可以自己制定下载路径

        //将下载请求加入下载队列
        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        //加入下载队列后会给该任务返回一个long型的id，
        //通过该id可以取消任务，重启任务等等，看上面源码中框起来的方法
        mTaskId = downloadManager.enqueue(request);
        //注册广播接收者，监听下载状态
        context.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }


    /**
     * 广播接受者，接收下载状态
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkDownloadStatus();//检查下载状态
        }
    };

    /**
     * 检查下载状态
     */
    private void checkDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(mTaskId);
        //筛选下载任务，传入任务ID，可变参数
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
//                    MLog.i(">>>下载暂停");
                    break;
                case DownloadManager.STATUS_PENDING:
//                    MLog.i(">>>下载延迟");
                    break;
                case DownloadManager.STATUS_RUNNING:
//                    MLog.i(">>>正在下载");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
//                    MLog.i(">>>下载完成");
                    //下载完成安装APK
                    if (downloadFinishInterface != null) {
                        downloadFinishInterface.downloadFinish(2);
                    }
                    String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                            + File.separator + versionName;
//                    SharedPreferenceUtils.getInstance(context).setUpdateVersion(false);
                    installAPK(new File(downloadPath));
                    break;
                case DownloadManager.STATUS_FAILED:
                    if (downloadFinishInterface != null) {
                        downloadFinishInterface.downloadFinish(2);
                    }
                    Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
                    ((Activity) context).finish();
//                    MLog.i(">>>下载失败");
                    break;
                default:
                    break;
            }
        }
    }

    protected void installAPK(File file) {
        Log.i("大小", "installAPK: " + file.length());
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public interface DownloadFinishInterface {
        void downloadFinish(int code);
    }

}
